package cn.jn.lhm.order.service.impl;

import cn.jn.lhm.order.entity.Order;
import cn.jn.lhm.order.entity.PayLog;
import cn.jn.lhm.order.mapper.OrderMapper;
import cn.jn.lhm.order.mapper.PayLogMapper;
import cn.jn.lhm.order.service.PayLogService;
import cn.jn.lhm.order.utils.HttpClient;
import cn.jn.lhm.service.config.exception.GlobalException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LHM
 * @Tips 热爱每一天，奋斗每一天
 * @date 2020/6/15 - 22:40
 */
@Service
@Slf4j
public class PayLogServiceImpl implements PayLogService {

    @Resource
    private PayLogMapper payLogMapper;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public Map<String, Object> createNative(String orderNum) {
        try {
            //1.根据订单编号查询订单信息
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNum);
            Order order = orderMapper.selectOne(wrapper);
            //2.使用map生成对应的二维码的信息
            Map<String, String> map = new HashedMap<>();
            map.put("appid", "wx74862e0dfcf69954");
            map.put("mch_id", "1558950191");
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            //课程标题
            map.put("body", order.getCourseTitle());
            //订单号
            map.put("out_trade_no", orderNum);
            //订单的价格
            map.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue() + "");
            //支付的IP地址，项目就是项目的域名
            map.put("spbill_create_ip", "127.0.0.1");
            //支付以后回调的地址
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            //根据价格生成二维码
            map.put("trade_type", "NATIVE");
            //3.发送请求生成二维码，传递xml参数，访问微信提供的地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            client.setXmlParam(WXPayUtil.generateSignedXml(map,
                    "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //使用post发送请求
            client.post();
            //获取响应结果
            String content = client.getContent();
            log.info("获取到的返回信息为：" + content);
            //将xml的返回格式转为map
           Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
           //最终返回数据的封装
            Map<String, Object> returnMap = new HashMap();
            returnMap.put("out_trade_no", orderNum);
            returnMap.put("course_id", order.getCourseId());
            returnMap.put("total_fee", order.getTotalFee());
            //返回二维码操作状态码
            returnMap.put("result_code", resultMap.get("result_code"));
            //二维码地址
            returnMap.put("code_url", resultMap.get("code_url"));
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(20001, "系统故障，二维码生成失败");
        }
    }

    @Override
    public Map<String, String> getOrderStatus(String orderNum) {
        try {
            //1、封装参数
            Map<String, String> m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNum);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2 发送httpclient
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            //3 得到请求返回内容
            String xml = client.getContent();
            //4.返回转换成的map返回
            return WXPayUtil.xmlToMap(xml);
        }catch(Exception e) {
            e.printStackTrace();
            throw new GlobalException(20001, "获取订单状态失败");
        }
    }

    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //根据订单号查询原有的数据
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", map.get("out_trade_no"));
        Order order = orderMapper.selectOne(wrapper);
        //更新订单状态
        if (order.getStatus() != 1){
            //设置支付成功
            order.setStatus(1);
            //更新数据
            orderMapper.updateById(order);

            //向支付表添加支付记录
            PayLog payLog = new PayLog();
            //订单号
            payLog.setOrderNo(map.get("out_trade_no"));
            //订单完成时间
            payLog.setPayTime(new Date());
            //支付类型 1微信
            payLog.setPayType(1);
            //总金额(分)
            payLog.setTotalFee(order.getTotalFee());
            //支付状态
            payLog.setTradeState(map.get("trade_state"));
            //流水号
            payLog.setTransactionId(map.get("transaction_id"));
            payLog.setAttr(JSONObject.toJSONString(map));
            //插入数据
            payLogMapper.insert(payLog);
        }
    }

    @Override
    public boolean getOrderInfo(String userId, String courseId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", userId);
        wrapper.eq("status", 1);
        Integer count = orderMapper.selectCount(wrapper);
        //返回支付结果，如果等于1则说明已经完成支付，否则就是未购买状态
        return count == 1;
    }


}
